import { Injectable } from '@angular/core';
import { NzMessageService, NzTreeNodeOptions } from 'ng-zorro-antd';
import { environment } from '@env/environment';
import { Observable } from 'rxjs';
import { ApiService } from '@core/services/api';
import { _HttpClient } from '@delon/theme';
import { CacheService } from '@delon/cache';
import { map } from 'rxjs/operators';
import { DicService } from '@core/services/dic.service';
export interface TreeOption {
  key: string,
  title: string,
  id: string,
  pId?: string,
  isLeaf?: boolean,
  sort?: number,
  [key: string]: any
}

@Injectable()
export class UtilService {
  get dicMap(): Map<string, {label, value}[]> {
    return  this.dic.dicMap
  };
  getStorage(key: string): string{
    return localStorage.getItem(key);
  }
  getStorageObj(key): object{
    return JSON.parse(localStorage.getItem(key) || '{}');
  }
  setStorage(key: string, data: any): void {
    localStorage.setItem(key, JSON.stringify(data));
  }

  /**
   * 组装nzTree 数据结构
   * @param arr 数组
   */
  getTreeNodeOption(arr: TreeOption[]): NzTreeNodeOptions[] {
    if (!arr || arr.length === 0) {
      return ;
    }
    arr.sort((a, b) => {
      return a.sort - b.sort;
    })
    arr.forEach(item => {
      if (item.pId) {
        const pNode = arr.find(value => value.id === item.pId);
        if (pNode) {
          if (pNode.children && Array.isArray(pNode.children) ) {
            if (!pNode.children.find(value => value.id === item.id))pNode.children.push(item);
          } else{
            pNode.children = [item]
          }
        }
      }
      const childNode = arr.find(value => value.pId === item.id);
      if (!childNode) {
        item.isLeaf = true;
      }
    })
    const obj = [];
    for (const item of arr) {
      if (!item.pId) {
        obj.push(item)
      }
    }
    return obj;
  }

  /**
   * 导出文件
   * @param path 路径
   */
  export(path: string) {
    if (!path) {
      this.msg.error('路径不能为空!');
      return;
    }
    window.location.href = environment.SERVER_URL + '/' + path;
  }

  /**
   * 上传文件
   * @param fileType 文件类型 1 excel 2、photo 3、pdf 4、word 5、其他
   * @param functionType 功能类型 1、车 2、人 3、房 4、设备
   * @param file 文件
   */
  uploadFile(fileType: string, functionType: string, file: File): Observable<any> {
    const body = new FormData();
    body.append('fileType', fileType);
    body.append('functionType', functionType);
    body.append('file', file)
    return this.http.post(this.api.util.uploadFile.url, body)
  }

  /**
   * 获取字典
   */
  getDic(): void {
    this.http.request<any>(this.api.dic.list.method, this.api.dic.list.url, {body: {status: 1}}).subscribe(res => {
      /* 字典处理开始 */
      const dicMap: Map<string, {label, value}[]> = new Map();
      res.data.map(item => {
        const obj = {label: item.dictCode, value: Number(item.dictCodeValue)};
        if (dicMap.has(item.shineField)) {
          const arr = dicMap.get(item.shineField);
          arr.push(obj);
          dicMap.set(item.shineField, arr)
        } else {
          dicMap.set(item.shineField, [obj])
        }
      })
      this.dic.dicMap = dicMap;
    })
  }
  /**
   * 将list字典转map
   * @param dic 字典list；
   */
  getObjDic(dic: string | Array<{label, value}>) : Map<any, any>{
    if (typeof dic === 'string') {
      dic = this.dic.dicMap.get(dic);
    }
    const res = new Map();
    dic.forEach(item => {
      res.set(item.value, item.label);
    })
    return res;
  }

  /**
   * object 转map
   * @param obj 对象
   */
  objToMap(obj: {}): Map<any, any> {
    return new Map(Object.entries(obj));
  }
  getDicByField(field): Observable<Array<{label, value}>> {
    return this.cache.get<any>(this.api.dic.getDic.url + field).pipe(map(res => {
        return res.data.map(item => {
          return {value: item.dictCode, label: item.dictCodeValue}
        })}
      ))
  }
  constructor(
    private msg: NzMessageService,
    private api: ApiService,
    private http: _HttpClient,
    private cache: CacheService,
    private dic: DicService
  ) {
  }
}
